package com.boardgame.users.service;



import com.boardgame.users.dto.PlayerInfoDto;
import com.boardgame.users.entity.PlayerInfo;
import com.boardgame.users.repository.PlayerInfoRepository;
import com.boardgame.users.security.ContextUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by pdybka on 16.05.16.
 */
@Service
@Transactional
public class PlayerInfoService {

    private final PlayerInfoRepository playerRepository;
    private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Autowired
    public PlayerInfoService(PlayerInfoRepository playerRepository) {
        this.playerRepository = playerRepository;
    }

    public PlayerInfo createNewPlayer(PlayerInfoDto playerDTO) {
        PlayerInfo newPlayer = new PlayerInfo();
        newPlayer.setUserName(playerDTO.getUserName());
        newPlayer.setPassword(passwordEncoder.encode(playerDTO.getPassword()));
        newPlayer.setEmail(playerDTO.getEmail());
        playerRepository.save(newPlayer);
        return newPlayer;
    }

    /**
     * 获取登录用户
     * @return
     */
    public PlayerInfo getLoggedUser() {
        PlayerInfo playerInfo = playerRepository.findOneByUserName("ala");
        return playerInfo;
        //ContextUser principal = (ContextUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //return playerRepository.findOneByUserName(principal.getPlayer().getUserName());
    }

    public List<PlayerInfo> listPlayers() {
        List<PlayerInfo> players = (List<PlayerInfo>) playerRepository.findAll();
        return players;
    }


}

